// pages/mine/mine/mine.js
import {getCollect,getFollow,recommendItem} from '../../../utils/api'
const app = getApp()
import Dialog from '../../../miniprogram_npm/@vant/weapp/dialog/dialog';
let winWidth = 414;
let winHeight = 736;
function deepClone(obj) {
  if (typeof obj !== 'object' || obj === null) {
    return obj
  }
  let newObj = obj instanceof Array ? [] : {}
  for (let key in obj) {
    if (obj.hasOwnProperty(key)) {
      newObj[key] = typeof obj[key] === 'object' ? deepClone(obj[key]) : obj[key]
    }
  }
  return newObj
}
Page({

  /**
   * 页面的初始数据
   */
  data: {
    arr:[
      {title:'滑动推荐项目'}
    ],
    mine_item: [{
        id: 0,
        mine_img: '../../../images/简历.png',
        mine_item: '简历',
      },
      {
        id: 1,
        mine_img: '../../../images/项目.png',
        mine_item: '项目',
      },
      {
        id: 2,
        mine_img: '../../../images/反馈.png',
        mine_item: '反馈',
      },
    ],
    head: {
      msg: '我的',
    },
    userImg: 'https://img.yzcdn.cn/vant/cat.jpeg',
    nickName: '',
    navBarHeight: app.globalData.navBarHeight,
    height: '',
    src: 'https://i.loli.net/2021/03/25/FYc75QLUO4fVe3h.png',
    x: winWidth,
    y: winHeight,
    animationA: {},
    list: [],
    distance: "",
    startX: '', // 初始点X位置
    startY: '', // 初始点Y位置
    currentIndex: -1, // 当前最上层滑块
    ratio: 2, // 屏幕比例
    token: null,
    focusTime:0,
    collectTime:0,
    collectMsg:[],
    focusMsg:[],
    users : []
    // slider
  },
  toMineItem: function (e) {
    let id = e.currentTarget.dataset.id
    if (id == 0) {
      wx.navigateTo({
        url: '../mine_resume/mine_resume',
      })
    } else if (id == 1) {
      wx.navigateTo({
        url: '../mine_item/mine_item',
      })
    } else if (id == 2) {
      wx.navigateTo({
        url: '../mine_feedback/mine_feedback',
      })
    }
  },
  toMineFocus: function () {
    let focusMsg = this.data.focusMsg
    focusMsg = JSON.stringify(focusMsg)
    wx.navigateTo({
      url: '../mine_focus/mine_focus?focusMsg='+focusMsg,
    })
  },
  toMineCollect: function () {
    let collectMsg = this.data.collectMsg
    collectMsg = JSON.stringify(collectMsg)
    wx.navigateTo({
      url: '../mine_collect/mine_collect?collectMsg='+collectMsg,
    })
  },
  //收藏数目
  getCollect(userId){
    getCollect(userId).then((res)=>{
      console.log('收藏数目',res);
      let collectTime = res.data.length
      let collectMsg = res.data
      this.setData({
        collectTime,
        collectMsg
      })
    })
  },
  moreItems(){
    wx.switchTab({
      url: '../../index/index/index',
    })
  },
  //关注数目
  getFollow(userId){
    getFollow(userId).then((res)=>{
      console.log('关注数目',res);
      let focusTime = res.data.length
      let focusMsg = res.data
      this.setData({
        focusTime,
        focusMsg
      })
    })
  },
  //获取用户信息
  getUserProfile(e) {
    return new Promise((resolve, reject) => {
      wx.getUserProfile({
        desc: '展示用户信息', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
        success: (res) => {
          this.setData({
            userImg: res.userInfo.avatarUrl,
            nickName: res.userInfo.nickName,
          })
          wx.setStorage({
            data: res.userInfo,
            key: 'userInfo',
          })
          resolve(res.userInfo)
        }
      })
    })
  },
  // 登录
async login() {
  let that = this
  const data = await that.getUserProfile
  data().then((userInfo) => {
    wx.login({
      success(res) {
        if (res.code) {
          wx.request({
            url: getApp().globalData.ip + '/user/login?code=' + res.code,
            data: {
              ...userInfo
            },
            method: 'POST',
            header: {
              'content-type': 'application/json;charset=utf-8',
            },
            dataType: 'json',
            success: (result) => {
              console.log('登录', result);
              wx.setStorageSync('user', result.data.data.user)
              wx.setStorageSync('TOKEN', result.data.data.token)
              wx.setStorageSync('userId', result.data.data.user.userId)
              that.setData({
                token: result.data.data.token
              })
              app.globalData.userId = result.data.data.user.userId
              that.onShow()
              that.onLoad()
            },
            fail: (err) => {
              console.log(err);
             }
           })
        } else {
           console.log('登录失败！' + res.errMsg)
         }
       }
    })
  })
},
onShow: function () {
  let user = wx.getStorageSync('userInfo')
    wx.request({
      url: getApp().globalData.ip + '/user/' + user.userId + '/follow',
      method: 'GET',
      success: (res) => {
        this.setData({
          users: res.data
        })
      }
    })
  let that = this
  let token = that.data.token
  let _token = wx.getStorageSync('TOKEN')
  let userInfo = wx.getStorageSync('userInfo')
  let userId = wx.getStorageSync('userId')
    // console.log('token',token);
    // console.log('_token',_token);
    // console.log('userInfo',userInfo);
    // console.log('用户信息',userInfo);

  if (_token === '') {
    Dialog.alert({
      title: '注意',
      message: '请进行授权登录!',
    }).then(() => {
        // on close
    });
  } else if (token === null) {
    app.globalData.userId = userId
    that.setData({
      token: _token,
      userImg: userInfo.avatarUrl,
      nickName: userInfo.nickName,
    })
  }
  if(userId){
    that.getFollow(userId)
    that.getCollect(userId)
  }
},
  /**
   * 生命周期函数--监听页面加载
   */
onLoad: function (options) {
  let that = this
  wx.getSystemInfo({
    success: function (res) {
      let height = 100 - ((that.data.navBarHeight) * 100) / res.screenHeight
      height = Math.floor(height)
      that.setData({
        height
      });
    }
   })
  let res = wx.getSystemInfoSync();
  winWidth = res.windowWidth;
  winHeight = res.windowHeight;
  let ratio = res.pixelRatio
  that.setData({
    ratio
  })
  that.getList()
  that.recommendItem()

},
touchStart(e) {
  let index = e.currentTarget.dataset.index
  let touches = e.touches
  let list = this.data.list || []
  // 多点触摸让图片回到原位
  if (touches.length > 1) {
    list[index].x = winWidth
    list[index].y = 0
    that.setData({
      list
    })
  } else if (index === (list.length - 1)) {
    let startX = e.touches[0].clientX;
    let startY = e.touches[0].clientY;
    this.setData({
      startX,
      startY
    })
  }
},
// 拖动结束
touchEnd(e) {
  let index = e.currentTarget.dataset.index
  let list = this.data.list || []
  if (index === (list.length - 1)) {
    let that = this;
    let startX = this.data.startX;
    let startY = this.data.startY;
    let endX = e.changedTouches[0].clientX;
    let endY = e.changedTouches[0].clientY;
    let distance = that.data.distance;
    // 与结束点与图片初始位置距离
    let disX = Math.abs(distance - winWidth)
    // 当前操作，初始点与结束点距离
    let disClientX = Math.abs(endX - startX)
    let disClientY = Math.abs(endY - startY)
    // 当滑动大于 滑块宽度的1/3翻页
    let ratio = this.data.ratio
    let moveDis = 666 / (ratio * 3);
    // console.log(disX, moveDis)
    if (disX > moveDis && disClientX > moveDis) {
      list[index].x = (endX - startX) > 0 ? winWidth * 2 : -winWidth
      // 移除时距离竖向距离
      // list[index].y = disClientY
      that.setData({
        list: list,
        animationA: null
      });
      // 移出动画结束后 从list内移除
      setTimeout(() => {
        list.splice((list.length - 1), 1);
        that.setData({
          list
        })
        // 列表长度小于9的时候请求服务端
        if (list.length < 9) {
          that.getList()
        }
      }, 300)
    } else if (disClientX < 1 && disClientY < 1) {
      let projectId = e.currentTarget.dataset.proid;
      if(projectId){
        wx.navigateTo({
          url: '../../index/detail/detail?projectId='+projectId,
        })
      }
    } else {
      list[index].x = winWidth
      list[index].y = 0
      that.setData({
         list
      })
    }
  }
},
touchMove(e) {
  // 左滑右滑手势可优化
  // console.log(123);
},
onChange: function (e) {
  let that = this;
  that.setData({
    distance: e.detail.x
  })
},
recommendItem(){  
  let userId = wx.getStorageSync('userId')
  if(userId){
    recommendItem(userId).then((res)=>{
      console.log(res.data);
      this.setData({
        arr:res.data
      })
    })
  }
},
// 模拟获取列表数据
getList() {
  wx.showLoading({
    title: '加载中',
  })
  setTimeout(() => {
    let list = this.data.list || [];
    let arr = this.data.arr
    arr = deepClone(arr)
    for (let i of arr) {
      i.x = winWidth
      i.y = 0
      list.unshift(i)
    }
    this.setData({
      list
    })
     wx.hideLoading()
  }, 200)
}
// slider
})